<script lang="ts" setup>
import type { WareHouse } from '#/api';

import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, InputSearch } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { addWareHouse, updateWareHouse } from '#/api';
import SearchChargeModal from '#/utils/view/user/chargeModal.vue';

import { useSchema } from './data';

const emit = defineEmits(['success']);
const formData = ref<WareHouse.Row>();
const title = ref<string>();
const searchValue = ref('');
const showConfrimBtn = ref(true);
const [Form, formApi] = useVbenForm({
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: useSchema(),
  showDefaultActions: false,
});

const getTitle = computed(() => {
  if (formData.value?.attr1 === '1') return '查看仓库设置';
  return formData.value?.attr1 === '2' ? '编辑仓库设置' : '新增仓库设置';
});
watch(getTitle, (newTitle) => {
  title.value = newTitle;
});

const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  destroyOnClose: true,
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();

      let data;
      await formApi.getValues().then((res) => {
        data = res;
      });
      try {
        await (formData.value?.warehouseId
          ? updateWareHouse(data!)
          : addWareHouse(data!));
        modalApi.close();
        emit('success', formData.value?.warehouseId ? '修改成功' : '新增成功');
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<WareHouse.Row>();
      if (data) {
        searchValue.value = data?.charge!;
        formData.value = data;
        formApi.setValues(formData.value);
        showConfrimBtn.value = formData.value?.attr1 !== '1';
        modalApi.setState({
          showConfirmButton: showConfrimBtn.value,
        });
      }
    }
  },
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues({});
}

// 用户搜索子弹框
const [SearchModal, searchModalApi] = useVbenModal({
  connectedComponent: SearchChargeModal,
  onClosed() {
    searchValue.value = searchModalApi.getData().userName;
    formApi.setFieldValue('charge', searchModalApi.getData().userName);
    formApi.setFieldValue('deptId', searchModalApi.getData().deptId);
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4">
      <template #charge>
        <InputSearch
          placeholder="请选择负责人"
          @search="searchModalApi.open()"
          readonly
          v-model:value="searchValue"
        />
      </template>
    </Form>
    <template #prepend-footer>
      <div class="flex-auto" v-if="showConfrimBtn">
        <Button type="primary" danger @click="resetForm"> 重置 </Button>
      </div>
    </template>
    <SearchModal> modal content </SearchModal>
  </Modal>
</template>
